<template>
<div>
  <div class="box box-custom">
    <div class="box-header with-border">
      <h3 class="box-title">问卷管理</h3>
      <button type="button" class="btn btn-custom pull-right left10" v-on:click="showAdd(2)">新建机构评估问卷</button>
      <!-- button type="button" class="btn btn-custom pull-right left10" v-on:click="showAdd(1)">新建健康评估问卷</button -->
    </div>
    <div class="box-body">
      <el-table class="table table-bordered"
        style="width: 100%"
        size="mini"
        border
        stripe
        highlight-current-row
        :data="questionnaireList"
        >
          <el-table-column prop="suName" label="问卷名称" width="200">
          </el-table-column>
          <el-table-column label="产品分类" width="220">
            <template slot-scope="scope">
              {{ (scope.row.typeId ? $store.getters.getDictionary.productType[scope.row.typeId] : '') }}
            </template>
          </el-table-column>
          <el-table-column prop="description" label="问卷描述">
          </el-table-column>
          <el-table-column label="操作" width="300">
            <template slot-scope="scope">
              <el-button size="mini" type="text" @click="previewQuest(scope.$index, scope.row)">
                <i class="el-icon-view"></i> 预览
              </el-button>
              <el-button size="mini" type="text" v-if="!scope.row.readOnly" @click="showEdit(scope.$index, scope.row)">
                <i class="el-icon-edit"></i> 编辑
              </el-button>
              <el-button size="mini" type="text" v-if="!scope.row.readOnly" @click="delQuestionnaire(scope.$index, scope.row)">
                <span class="danger"><i class="el-icon-delete"></i> 删除</span>
              </el-button>
            </template>
          </el-table-column>
        </el-table>
    </div>
  </div>
  <el-dialog width="80%"
  :title="dialogTitle"
  :visible.sync="dialogVisible"
  :before-close="handleClose">
    <form class="form-horizontal">
    <table class="table table-bordered">
        <thead>
          <tr>
            <th class="textCenter" style="width: 40%">问卷基本信息</th>
            <th class="textCenter" style="width: 60%">题库选择</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td>
              <div class="input-group bottom10">
                <span class="input-group-addon">问卷名称</span>
                <input type="text" class="form-control" placeholder="" v-model="formData.suName">
              </div>
              <div class="input-group bottom10">
                <span class="input-group-addon">问卷类别</span>
                <span class="form-control">
                  {{ $store.getters.getDictionary.productType[formData.typeId] }}
                </span>
              </div>
              <div class="input-group bottom10">
                <span class="input-group-addon">问卷描述</span>
                <input type="text" class="form-control" placeholder="" v-model="formData.description">
              </div>
              <div class="input-group bottom10">
                <span class="input-group-addon">禁用</span>
                <div class="checkbox form-control">
                  <label>
                    <input type="checkbox" v-model="formData.disabled" />
                  </label>
                </div>
                <!-- el-switch class="form-control" v-model="formData.disabled"></el-switch -->
              </div>
            </td>
            <td>
              <el-tree ref="questionsSelectTree" v-if="questionsTree.length" style="width:100%; height:290px; overflow-y: scroll;"
                highlight-current
                default-expand-all
                node-key="questionId"
                show-checkbox
                :expand-on-click-node="false"
                :data="questionsTree"
                :default-checked-keys="formData.questionIds">
                <span class="custom-tree-node" slot-scope="{ node, data }">
                  <span class="table_td">{{ data.name }}</span>
                </span>
              </el-tree>
            </td>
          </tr>
        </tbody>
      </table>
      <div class="textCenter">
        <button type="button" class="btn btn-custom" v-on:click="onSubmit()">保存</button>
      </div>
      </form>
  </el-dialog>
  <el-dialog width="80%"
  title="预览问卷"
  :visible.sync="showQuestionnaireDialog"
  :before-close="handleClose">
    <showQuestionnaire :questionnaireData="showQuestionnaireData"></showQuestionnaire>
  </el-dialog>
</div>
</template>
<script>
import showQuestionnaire from './previewQuestionnaire.vue'

export default {
  name: 'questionnaire',
  data () {
    return {
      questionnaireList: [],
      // 健康评估题库
      healthQuestionsTree: [],
      // 机构评估题库
      orgQuestionsTree: [],
      // 可选择题库
      questionsTree: [],
      dialogVisible: false,
      dialogTitle: '',
      formData: {},
      editDataIndex: null,
      // 预览问卷
      showQuestionnaireDialog: false,
      showQuestionnaireData: {}
    }
  },
  props: {
  },
  components: {
    showQuestionnaire
  },
  methods: {
    getQuestionnaireList () {
      this.$http.get('listSurvey').then(
        response => {
          this.questionnaireList = response.data.data
        }        
      )
    },
    getQuestionsTree (typeId) {
      this.$http.get('question/listCategoryAndQuestion?typeId=' + typeId).then(
        response => {
          response.data.data.map(
            primaryCategory => {
              if (primaryCategory.children.length > 0) {
                primaryCategory.children.map(
                  secondCategory => {
                    if (secondCategory.questions && secondCategory.questions.length > 0) {
                      secondCategory.children = secondCategory.questions.map(
                        item => {
                          return {questionId: item.id, id: item.id, categoryId: item.categoryId, name: item.quName, readOnly: item.readOnly, disabled: item.disabled}
                        }
                      )
                    }
                  }
                )
              }
            }
          )
          if (typeId === 1) {
            this.healthQuestionsTree = response.data.data
          } else if (typeId === 2) {
            this.orgQuestionsTree = response.data.data
          }
        }
      )
    },
    getAllQuestions () {
    },
    addQuestionnaire () {
      this.$alert('正在保存...', '', true)
      this.$http.post('saveSurvey', this.formData).then(
        response => {
          this.getQuestionnaireList()
          this.$alert(response.data.message, '', true)
          this.dialogVisible = false
        }
      )
    },
    updataQuestionnaire () {
      this.$alert('正在保存...', '', true)
      this.$http.put('updateSurvey', this.formData).then(
        response => {
          this.getQuestionnaireList()
          this.$alert(response.data.message, '', true)
          this.dialogVisible = false
        }
      )
    },
    delQuestionnaire (index, rowData) {
      if (confirm('确认删除？') === false ) return false
      this.$http.delete('deleteSurvey?suId=' + rowData.id).then(
        response => {
          alert(response.data.message)
          this.questionnaireList.splice(index, 1)
        }
      )
    },
    showAdd (typeId) {
      this.dialogTitle = '新建问卷'
      this.formData = {}
      this.formData.typeId = typeId
      if (typeId === 1) {
        this.questionsTree = this.healthQuestionsTree
      } else if (typeId === 2) {
        this.questionsTree = this.orgQuestionsTree
      }
      this.dialogVisible = true
      // 清空所有选项
      this.$refs.questionsSelectTree.setCheckedKeys([])
    },
    showEdit (index, row) {
      this.dialogTitle = '修改问卷'
      this.formData = {}
      this.editDataIndex = index
      this.formData = JSON.parse(JSON.stringify(row))
      if (this.formData.typeId === 1) {
        this.questionsTree = this.healthQuestionsTree
      } else if (this.formData.typeId === 2) {
        this.questionsTree = this.orgQuestionsTree
      }
      this.dialogVisible = true
      // 将已存在的问题设置为选择状态
      this.$refs.questionsSelectTree.setCheckedKeys(this.formData.questionIds)
    },
    onSubmit () {
      let checkedArr = this.$refs.questionsSelectTree.getCheckedNodes()
      let questionIds = []
      checkedArr.map((item)=>{
        // 如果存在categoryId则item是一个问题，添加其id到 
        if (item.categoryId) { questionIds.push(item.id) }
      })
      // console.log(questionIds)
      this.formData.questionIds = questionIds
      this.formData.id ? this.updataQuestionnaire() : this.addQuestionnaire()
    },
    handleClose (done) {
      this.$confirm('确认关闭？').then(_ => { done() }).catch(_ => {})
    },
    previewQuest (index, row) {
      this.$alert('正在加载', '加载问卷内容', true)
      this.$http.get('getSurveyQuDetail?suId=' + row.id).then(
        response => {
          this.showQuestionnaireData = response.data.data
          this.$alert('正在完成', '', false)
          this.showQuestionnaireDialog = true
        }
      )
    }
  },
  beforeCreate () {},
  created () {},
  beforeMount () {},
  mounted () {
    this.getQuestionnaireList()
    // this.getQuestionsTree(1)
    this.getQuestionsTree(2)
  },
  beforeUpdate () {},
  updated () {},
  beforeDestroy () {},
  destroyed () {}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.custom-tree-node{margin-right: 10px;}
</style>
